<template>
  <view class="depositDetailPage-container1033">


    <view class="order-wrapper">
      <!-- 订单列表数据 -->
      <scroll-view
          v-if="orderList.length"
          scroll-y="true"
          @scrolltolower="scrolltoBottomHandler"
          class="orderListWrapper"
      >
        <view
            v-for="orderObj in orderList"
            class="order-item"
            :key="orderObj.id"
        >
          <view class="topItem">
            <text class="created-time">{{ orderObj.orderCreateTime }}</text>
            <text :class="{'status-cn': true, isRed: isStatusCnAlertColor(orderObj)}">{{ statusCn(orderObj.status) }}</text>
          </view>
          <view class="center" @click="goProductDetail(orderObj.orderId)">
            <image :src="orderObj.productImgSrc" class="left" />
            <view class="right">
              <view class="c-top">{{ orderObj.productName }}</view>
              <view class="c-center">{{orderObj.shopAdditionalServicesName}}：¥{{ orderObj.price }}</view>
            </view>
          </view>
          <view v-if="checkShowBottomArea(orderObj)" class="bottom">
            <view
                v-if="checkIsShowSingleOrderQuZhifu(orderObj)"
                @click="quzhifuHandler(orderObj)"
                class="btn btn2"
            >
              去支付
            </view>
          </view>
        </view>
        <view class="be-end" v-if="hasBeenEnd && !loading">已经到底了~</view>
      </scroll-view>

    <view v-if="!loading && !orderList.length"  class="empty-text">暂无补充增值服务订单</view>

    </view>

  </view>
</template>

<script>
import { tradePay } from "../../utils/platform"
import {
  checkOrderNeedPay,
  checkOrderNeedShouhuo, checkOrderOverdue, checkOrderSettle,
  getOrderId
} from "../../components/orderItem/orderActionBtns/utils/checkShowBtn";
import {EMPTY_PLACEHOLDER, orderStatusNumber2Cn} from "../../utils/constant";
const defaultApiRes = {
  records: [], // 订单列表
}

export default {
  data() {
    return {
      loading: true, // 请求页面数据中
      orderListApiRes: defaultApiRes,
      zhifuFetching: false, // 支付中
      pageNumber: 1,
      pageSize: 10,
      statusEnum:{
        "WAITING_PAYMENT":"待支付",
        "PAID":"已支付",
        "REFUNDED":"已退款",
        "CLOSED":"已关闭",
      }
    }
  },

  onLoad(e) {
    this.fetchOrderListHandler()
  },

  /**
   * 监听页面的下拉刷新操作
   */
  onPullDownRefresh() {
    this.refreshHandler(true)
  },

  computed: {
    // 加工过后订单列表数据，不管接口返回如何，一定能确保其数据类型是数组，使用方无需检测
    orderList: function() {
      const resObj = this.orderListApiRes || {}
      return (resObj && resObj.records) || []
    },
    // 判断是否已经到最后一页了
    hasBeenEnd: function() {
      const totalPages = this.orderListApiRes?.pages || 2 // 这里把初始值设置为2，是为了避免一开始就不请求（这样写不太好）
      return this.pageNumber >= totalPages && !this.loading
    },
    /**
     * 判断状态是否是红色
     */
    isStatusCnAlertColor: function() {
      return (parameter) =>{
        return parameter && parameter.status=="WAITING_PAYMENT"
      }
    },
    /**
     * 获取到状态的中文名称
     */
    statusCn: function() {
      return (parameter)=>{
        const cn = this.statusEnum[parameter]
        return cn || EMPTY_PLACEHOLDER
      }
    },
  },

  methods: {
    /**
     * 刷新处理
     */
    refreshHandler(isPullDownRefresh) {
      this.resetHandler()
      this.fetchOrderListHandler(isPullDownRefresh)
    },
    // 初始化数据
    resetHandler() {
      this.pageNumber = 1
      this.orderListApiRes = {}
    },

    /**
     * 跳转到订单详情页面
     */
    goProductDetail(orderId) {
      this.$onTo(`/pages/orderDetail/orderDetail?orderId=${orderId}`)
    },

    /**
     * 加载账单列表数据
     * @param {Boolean} isRefresh : 是否使用在刷新的场景中
     */
    fetchOrderListHandler(isPullDown) {
      const stopPulldownHandler = () => {
        isPullDown && uni.stopPullDownRefresh()
      }

      this.loading = true

      if (this.hasBeenEnd) { // 已经到底部了，那么直接返回
        stopPulldownHandler()
        return
      }

      const postObj = {
        uid: this.$getUid(),
        pageNumber: this.pageNumber,
        pageSize: this.pageSize,
      }
      const cnMap = { uid: "用户ID", pageNumber: "页数", pageSize: "页码" }
      const { postData, pass } = this.$postDataGuard(postObj, cnMap)
      if (!pass) { // 说明参数校验失败
        stopPulldownHandler()
        return
      }

      uni.showLoading({ title: "加载中" })
      this.$request("hzsx/api/order/extraAdditionalServicesOrderList", postData, "POST", false, true).then(res => {
        const resData = res.data || {}
        resData.records = this.compositeOrderList(resData)
        this.orderListApiRes = resData || defaultApiRes

      }).finally(() => {
        this.loading = false
        uni.hideLoading()
        stopPulldownHandler()
      })
    },



    /**
     * 合成新的订单列表数据
     * @param {newV} 新请求到的接口数据
     */
    compositeOrderList(newV) {
      const currentOrderList = this.orderList
      const newOrderList = newV?.records || []
      return [...currentOrderList, ...newOrderList]
    },

    /**
     * 判断是否有订单列表数据
     */
    checkHasBillList() {
      return this.orderListApiRes?.records?.length
    },


    /**
     * 判断单个订单是否显示去支付按钮
     * @param {*} oObj : 单个订单对象
     */
    checkIsShowSingleOrderQuZhifu(oObj) {
      return oObj?.status=='WAITING_PAYMENT' // 有待支付的押金时才显示该按钮
    },

    /**
     * 判断是否显示订单模块的底部按钮区域
     * @param {*} orderObj : 单个订单对象
     */
    checkShowBottomArea(orderObj) {
      return this.checkIsShowSingleOrderQuZhifu(orderObj)
    },


    /**
     * 支付当个订单的时候触发
     * @param {*} oObj : 订单对象
     */
    quzhifuHandler(oObj) {
      if (this.zhifuFetching) return
      const { id } = oObj
      this.zhifuFetching = true
      uni.showLoading({ title: "支付中" })

      const failedToast = () => {
        this.zhifuFetching = false
        uni.hideLoading()
        uni.showToast({ title: "支付失败" })
      }

      this.$request(`hzsx/orderExtraAdditionalServices/getPayInfo?id=${id}`, {}, "get").then(res => {
        this.zhifuFetching = false
        const resData = res.data
        if (!resData || !resData.payUrl) {
          uni.hideLoading()
          uni.showToast({ title: "缺少付款流水号，请重试" })
          return
        }
        tradePay(resData.payUrl, true).then(res => {
          if (res.resultCode === "9000") { // 表明支付成功
            setTimeout(() => {
              uni.hideLoading()
              uni.showToast({ title: "支付成功" })
              this.refreshHandler(true)
            }, 2500) // 增加延时，避免后端接受支付宝回调不及时
          } else {
            failedToast()
          }
        }).catch(() => {
          failedToast()
        })
      }).catch(() => {
        failedToast()
      })
    },

    /**
     * 监听滑动到底部
     */
    scrolltoBottomHandler() {
      if (this.hasBeenEnd) return
      this.pageNumber++
      this.fetchOrderListHandler()
    }

  }
}
</script>

<style lang="scss" scoped>
.depositDetailPage-container1033 {
  min-height: 100vh;
  background: #F3F4F4;
  box-sizing: border-box;
  padding: 20rpx;
  padding-bottom: 140rpx;
  .top-tip {
    background: #FFF9E3;
    border-radius: 20rpx;
    padding: 17rpx 20rpx;
    font-size: 24rpx;
    font-family: PingFangSC-Regular, PingFang SC;
    font-weight: 400;
    color: #986828;
    line-height: 33rpx;
    margin-bottom: 30rpx;
  }
  .order-wrapper {
    .order-item + .order-item {
      margin-top: 20rpx;
    }
    .orderListWrapper {
      box-sizing: border-box;
      padding-top: 0;
      // padding-bottom: 20rpx;
      height: calc(100vh - 90rpx);
    }
    .be-end {
      height: 80rpx;
      line-height: 80rpx;
      text-align: center;
      font-size: 28rpx;
      font-family: PingFangSC-Regular, PingFang SC;
      font-weight: 400;
      color: #999;
    }
    .order-item {
      background: #FFFFFF;
      border-radius: 20rpx;
      box-sizing: border-box;
      padding: 0 30rpx;
      .topItem {
        display: flex;
        justify-content: space-between;
        height: 0.7rem;
        -webkit-box-align: center;
        -webkit-align-items: center;
        align-items: center;
        .created-time {
          font-size: 24rpx;
          font-family: PingFangSC-Regular, PingFang SC;
          font-weight: 400;
          color: #333333;
        }
        .status-cn {
          font-size: 28rpx;
          font-family: PingFangSC-Regular, PingFang SC;
          font-weight: 400;
          color: #999999;
        }
        .isRed {
          color: #E52021;
        }
      }
      .top {
        height: 70rpx;
        display: flex;
        align-items: center;
        font-size: 24rpx;
        font-family: PingFangSC-Regular, PingFang SC;
        font-weight: 400;
        color: #999999;
      }
      .center {
        padding: 30rpx 0;
        border-top: 1rpx solid #F5F6F6;
        border-bottom: 1rpx solid #F5F6F6;
        display: flex;
        align-items: center;
        .left {
          width: 150rpx;
          height: 150rpx;
          margin-right: 30rpx;
        }
        .right {
          .c-top {
            font-size: 24rpx;
            font-family: PingFangSC-Medium, PingFang SC;
            font-weight: 500;
            color: #222222;
            margin-bottom: 30rpx;
            line-height: 33rpx;
          }
          .c-center, .c-bottom {
            font-size: 28rpx;
            font-family: PingFangSC-Regular, PingFang SC;
            font-weight: 400;
            color: #666666;
            line-height: 33rpx;
          }
          .c-center {
            margin-bottom: 10rpx;
          }
        }
      }
      .bottom {
        height: 94rpx;
        display: flex;
        align-items: center;
        justify-content: flex-end;
        font-size: 24rpx;
        font-family: PingFangSC-Medium, PingFang SC;
        font-weight: 500;
        .btn {
          display: flex;
          align-items: center;
          justify-content: center;
          width: 138rpx;
          height: 56rpx;
          border-radius: 30rpx;
        }
        .btn1 {
          background: #FFFFFF;
          color: #333333;
          border: 1rpx solid #C0C0C0;
        }
        .btn2 {
          background: linear-gradient(90deg, #FD5C5A 0%, #FF2401 100%);
          color: #FFFFFF;
        }
        .btn+.btn {
          margin-left: 20rpx;
        }
      }
    }
  }
  .dialog-wrapper {
    .mask {
      position: fixed;
      top: 0;
      bottom: 0;
      left: 0;
      right: 0;
      background: rgba(0, 0, 0, 0.5);
      z-index: 3;
    }
    .content-wrapper {
      position: fixed;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      width: 600rpx;
      height: 406rpx;
      background: #FFFFFF;
      border-radius: 20rpx;
      z-index: 4;
      .top-text {
        position: absolute;
        font-size: 36rpx;
        font-family: PingFangSC-Medium, PingFang SC;
        font-weight: 500;
        color: #222222;
        top: 87rpx;
        left: 50%;
        transform: translateX(-50%);
        white-space: nowrap;
      }
      .contentip1, .contentip2, .contentip1-0, .contentip1-1 {
        font-size: 24rpx;
        font-family: PingFangSC-Regular, PingFang SC;
        font-weight: 400;
        color: #606370;
        position: absolute;
        left: 50%;
        transform: translateX(-50%);
        white-space: nowrap;
      }
      .contentip1, .contentip1-0 {
        top: 172rpx;
      }
      .contentip2, .contentip1-1 {
        top: 210rpx;
      }
      .contentip1-0, .contentip1-1 {
        left: 115rpx;
        transform: translateX(0);
      }
      .submit-btn {
        width: 498rpx;
        height: 80rpx;
        background: linear-gradient(90deg, #FD5C5A 0%, #FF2401 100%);
        border-radius: 40rpx;
        display: flex;
        align-items: center;
        justify-content: center;
        position: absolute;
        left: 50%;
        transform: translateX(-50%);
        bottom: 39rpx;
        font-size: 28rpx;
        font-family: PingFangSC-Medium, PingFang SC;
        font-weight: 500;
        color: #FFFFFF;
      }
    }
  }
  .empty-text {
    text-align: center;
    margin-top: 119rpx;
    font-size: 32rpx;
    font-family: PingFangSC-Regular, PingFang SC;
    font-weight: 400;
    color: #222222;
  }
  .closeImg {
    width: 21rpx;
    height: 21rpx;
    border: 20rpx solid transparent;
    position: absolute;
    top: 10rpx;
    right: 10rpx;
  }
}
</style>
